package com.marvin.springBoot.service;

import com.marvin.springBoot.configuration.readAndWrite.annotation.TargetDataSource;
import com.marvin.springBoot.persistence.DemoUserEntity;
import com.marvin.springBoot.persistence.DemoUserType;
import com.marvin.springBoot.repository.IBaseRepository;
import com.marvin.springBoot.repository.impl.DemoRepositoryImpl;
import com.marvin.springBoot.repository.support.Query;
import com.marvin.springBoot.repository.user.DemoUserRepositoryImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import java.util.List;

/**
 * @author marvin.ma
 * @create 2017-09-28 8:44
 * @desc demo service
 **/
@Service
public class DemoService {

    @Resource
    private DemoRepositoryImpl demoDao;

    @Resource
    private IBaseRepository baseDao;

    //@Resource
    //private DemoUserRepositoryImpl demoUserRepositoryImpl;

    public DemoUserEntity selectById(long id) {
        return demoDao.selectById(DemoUserEntity.class, id);
    }

    //public List<DemoUserEntity> selectByName(String name) {
    //    return demoUserRepositoryImpl.findUserByName(name);
    //}

    public DemoUserEntity selectByQuery(long id) {
        return baseDao.queryById(DemoUserEntity.class, id);
    }

    public List<DemoUserEntity> selectAll() {
        return baseDao.queryAll(DemoUserEntity.class);
    }

    @TargetDataSource(dataSource = "readDruidDataSource")
    public DemoUserEntity selectByIdInReadDataBase(long id) {
        return demoDao.selectById(DemoUserEntity.class, id);
    }

    public List<DemoUserEntity> selectByConditions(long id, String name, String sex, String type, String address) {
        Query query = baseDao.forClass(DemoUserEntity.class);
        if (0 != id) {
            query.eq("id", id);
        }
        if (StringUtils.isNotEmpty(name)) {
            query.eq("name", name);
        }
        if (StringUtils.isNotEmpty(sex)) {
            query.eq("sex", sex);
        }
        if (StringUtils.isNotEmpty(type)) {
            //测试join方法
            Join<DemoUserEntity, DemoUserType> join = query.getFrom().join("userType");
            Join<DemoUserEntity, DemoUserType> leftJoin = query.getFrom().join("userType", JoinType.LEFT);
            query.getCriteriaQuery().where(query.getCriteriaBuilder().equal(leftJoin.get("typeId"), type));
        }
        if (StringUtils.isNotEmpty(address)) {
            query.like("address", address);
        }
        List<DemoUserEntity> list = baseDao.query(query);
        return list;
    }
}
